//
//  PersonalSettingVC.m
//  PrivateSteward
//
//  Created by lanou3g on 16/3/29.
//  Copyright © 2016年 闫贺晨. All rights reserved.
//

#import "PersonalSettingVC.h"

@interface PersonalSettingVC ()<UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@end

@implementation PersonalSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    self.view.backgroundColor = [UIColor whiteColor];
}
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.title = @"个人设置";
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(doneAction)];
    if (self.isReSet == NO) {
        AVQuery *query = [AVQuery queryWithClassName:@"UserClass"];
        [query whereKey:@"phoneNumber" equalTo:[AVUser currentUser].username];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (objects.count > 0 ) {
                self.myimageview.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objects[0][@"localData"][@"userImageUrl"]]]];
                self.usernametextfiled.text =  objects[0][@"localData"][@"username"];
            }
        }];
        self.usernametextfiled.text = [[AVUser currentUser]username];
    }
   
}
-(void)doneAction
{
    AVQuery *query = [AVQuery queryWithClassName:@"UserClass"];
    [query whereKey:@"phoneNumber" equalTo:[[AVUser currentUser] username]];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects.count > 0) {
            NSData *imageData = UIImageJPEGRepresentation(self.myimageview.image, 0.1);
            AVFile *file = [AVFile fileWithData:imageData];
            [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    AVObject *obj = [AVObject objectWithoutDataWithClassName:@"UserClass" objectId:[objects[0] objectId]];
                    [obj setObject:self.usernametextfiled.text forKey:@"username"];
                    [obj setObject:file.url forKeyedSubscript:@"userImageUrl"];
                    
                    [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        [self alertAction:@"个人信息" messageString:@"已修改成功"];
                        self.isReSet = NO;
                    }];
                }
                else
                {
                    [self alertAction:@"个人信息" messageString:@"修改失败"];
                }
            }];
        }
        else
        {
            [self alertAction:@"失败" messageString:@"查询失败"];
        }
    }];
    
    [[NSNotificationCenter defaultCenter ]postNotificationName:@"didlogin" object:nil];
}
- (void)callActionSheetFunc{
    
    //警告控制器
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        //初始化控制器
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        //设定sourceType样式
        imagePickerController.sourceType = sourceType;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        // 跳转到相机或相册页面
        [self presentViewController:imagePickerController animated:YES completion:^{
        }];
    }];
    
    UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        //来源:相册
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        // 跳转到相机或相册页面
        [self presentViewController:imagePickerController animated:YES completion:^{
        }];
        
    }];
    
    UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    //警告控制器添加点击事件
    [alertVC addAction:alertAction];
    [alertVC addAction:alertAction1];
    [alertVC addAction:alertAction2];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}
//获取相册照片代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    self.isReSet = YES;
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.myimageview.image = image;
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)initView
{
    self.myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.myView.backgroundColor = [UIColor colorWithRed:124/255.0 green:213/255.0 blue:254/255.0 alpha:1];
    [self.view addSubview:self.myView];
    
    self.myimageview = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2 - 50, 80, 100, 100)];
    self.myimageview.layer.cornerRadius = 50;
    self.myimageview.userInteractionEnabled = YES;
    self.myimageview.image = [UIImage imageNamed:@"default_account_userphoto_default@2x"];
    UITapGestureRecognizer *type = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapAction:)];
    [self.myimageview  addGestureRecognizer:type];
    [self.myView addSubview:self.myimageview];
    
    self.imageviewLable = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2 - 100, CGRectGetMaxY(self.myimageview.frame),200,  30)];
    self.imageviewLable.backgroundColor = self.myimageview.backgroundColor;
    self.imageviewLable.textAlignment = NSTextAlignmentCenter;
    self.imageviewLable.font = [UIFont systemFontOfSize:13];
    self.imageviewLable.textColor = [UIColor grayColor];
    self.imageviewLable.text = @"点击头像,设置个性头像";
    [self.myView addSubview:self.imageviewLable];
    
    self.usernameLable = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.imageviewLable.frame) + 30,60, 30)];
    self.usernameLable.backgroundColor = self.myView.backgroundColor;
    self.usernameLable.textColor = [UIColor grayColor];
    self.usernameLable.text = @"昵称";
    self.usernameLable.textAlignment = NSTextAlignmentCenter;
    [self.myView addSubview:self.usernameLable];
    
    self.usernametextfiled = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.usernameLable.frame), CGRectGetMinY(self.usernameLable.frame), self.myView.frame.size.width - self.usernameLable.frame.size.width, self.usernameLable.frame.size.height)];
    
    self.usernametextfiled.backgroundColor = [UIColor whiteColor];
    self.usernametextfiled.textAlignment = NSTextAlignmentLeft;
    self.usernametextfiled.delegate = self;
    self.usernametextfiled.clearsOnBeginEditing = NO;
    self.usernametextfiled.clearButtonMode = UITextFieldViewModeAlways;
    self.usernametextfiled.layer.cornerRadius = 8;
    [self.myView addSubview:self.usernametextfiled];
    
}
-(void)back
{
    //
    [self.navigationController popViewControllerAnimated:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.usernametextfiled resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)TapAction:(UIGestureRecognizer *)sender
{
    [self callActionSheetFunc];
}

-(void)alertAction:(NSString *)alertstring messageString:(NSString *)messageString
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:alertstring message:messageString preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
    }];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
